﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LogLib;
using ComLib.ComType;
using DeviceCommon;
using Newtonsoft.Json;
using System.IO;

namespace TestClient
{
    public partial class Form1 : Form
    {   
        public IDCardAll _cardInfo = new IDCardAll();

        public bool _bCardLibInited = false;

        private AsyncClient client = new AsyncClient();

        public Form1()
        {
            client.UpdateData += OnDataUpdated;
            client.DataReceived += OnDataReceived;
            InitializeComponent();
        }

        private void OnDataUpdated(string info)
        {
            if (this.InvokeRequired)
            {
                DataUpdatedHandler handler = new DataUpdatedHandler(OnDataUpdated);
                this.BeginInvoke(handler, new object[] { info });
                return;
            }
            labelErrorInfo.Text = info;
        }

        private void OnDataReceived(ResponseMsgPackge pack)
        {
            if (this.InvokeRequired)
            {
                ResponseDataReceivedHandler handler = new ResponseDataReceivedHandler(OnDataReceived);
                this.BeginInvoke(handler, new object[] { pack });
                return;
            }
            switch (pack.Action)
            {
                case DeviceAction.DoAction:
                    if (pack.Success)
                    {
                        OnDone(pack);
                    }
                    else
                    {
                        OnDoneFailed(pack);
                    }
                    break;
                case DeviceAction.Exit:
                    break;
                case DeviceAction.Init:
                    if (pack.Success)
                    {
                        OnInitOK(pack);
                    }
                    else
                    {
                        OnInitFailed(pack);
                    }
                    break;
                case DeviceAction.Start:
                    break;
                case DeviceAction.Stop:
                    break;
                case DeviceAction.Test:
                    break;
                case DeviceAction.Working:
                    break;
                default:
                    break;
            }
         
        }

        public void OnDone(ResponseMsgPackge pack)
        {
            IDCardAll cardInfo = JsonConvert.DeserializeObject<IDCardAll>(pack.OutParams);
            SetIDCardInfo(cardInfo);
        }

        public void OnDoneFailed(ResponseMsgPackge pack)
        {
            if (this.InvokeRequired)
            {
                Action<ResponseMsgPackge> handler = new Action<ResponseMsgPackge>(OnDoneFailed);
                this.BeginInvoke(handler, new object[] { pack });
                return;
            }
            labelErrorInfo.Text = "读取失败:" + pack.Message;
        }

        public void OnInitOK(ResponseMsgPackge pack)
        {
            if (this.InvokeRequired)
            {
                Action<ResponseMsgPackge> handler = new Action<ResponseMsgPackge>(OnInitOK);
                this.BeginInvoke(handler, new object[] { pack });
                return;
            }
            labelErrorInfo.Text = "阅读器初始化成功";
        }

        public void OnInitFailed(ResponseMsgPackge pack)
        {
            if (this.InvokeRequired)
            {
                Action<ResponseMsgPackge> handler = new Action<ResponseMsgPackge>(OnInitFailed);
                this.BeginInvoke(handler, new object[] { pack });
                return;
            }
            labelErrorInfo.Text = "阅读器初始化失败:" + pack.Message;
        }

        private void buttonReadCard_Click(object sender, EventArgs e)
        {
            OnRequesting(DeviceAction.DoAction);
        }

        private void SetIDCardInfo(IDCardAll cardInfo)
        {
            labelErrorInfo.Text = "读卡成功!";
            textBoxAddress.Text = cardInfo.address;
            textBoxBirthday.Text = cardInfo.birthday;
            textBoxSex.Text = cardInfo.sex;
            textBoxName.Text = cardInfo.name;
            textBoxVDate.Text = cardInfo.validtermOfStart + "-" + cardInfo.validtermOfEnd;
            textBoxDepartment.Text = cardInfo.signdate;
            textBoxNation.Text = cardInfo.people;
            textBoxIDNO.Text = cardInfo.number;
            if (File.Exists(cardInfo.HeadImage))
            {
                pictureBox1.Image = Image.FromFile(cardInfo.HeadImage);
            }            
        }

        private void buttonInit_Click(object sender, EventArgs e)
        {

            OnRequesting(DeviceAction.Init);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            OnRequesting(DeviceAction.Exit);
        }

        private void buttonTest_Click(object sender, EventArgs e)
        {          
          
        }

        private void OnRequesting(string action)
        {
            RequestMsgPackge pack = new RequestMsgPackge();
            pack.DeviceName = "IDCardReader";
            pack.Action = action;      
            byte[] dataBody = MsgPackHandler.ConvertToBytes<RequestMsgPackge>(pack);
            // 协议命令占16位, 如果占的位数长过协议，那么协议解析会出错的
            var commandData = Encoding.UTF8.GetBytes(action);
            // 长度int类型占4位，根据协议这里也只能4位，否则会出错
            var dataLen = BitConverter.GetBytes(dataBody.Length);
            // 命令加内容长度为20
            var sendData = new byte[20 + dataBody.Length];
            // +-------+---+-------------------------------+
            // |request | l |                               |
            // | name   | e |    request body               |
            // |  (16 )   | n |                               |
            // |            |(4)|                               |
            // +-------+---+-------------------------------+
            Array.ConstrainedCopy(commandData, 0, sendData, 0, commandData.Length);
            Array.ConstrainedCopy(dataLen, 0, sendData, 16, 4);
            Array.ConstrainedCopy(dataBody, 0, sendData, 20, dataBody.Length);
            client.Send(sendData);
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            client.Start();
        }
    }

      //Encoding encode0 = Encoding.GetEncoding("ASCII");                   
      //      Encoding encode1 = Encoding.GetEncoding("Unicode");
      //      Encoding encode2 = Encoding.GetEncoding("UTF-8");
      //      Encoding encode3 = Encoding.GetEncoding("UTF-32");
      //      Encoding encode4 = Encoding.GetEncoding("GBK");
      //      Encoding encode5= Encoding.GetEncoding("GB2312");
      //      Encoding encode6 = Encoding.GetEncoding("BIG5");
      //      Encoding encode8 = Encoding.GetEncoding("hz-gb-2312");
      //      Encoding encode9 = Encoding.GetEncoding("GB18030");
      //      Encoding encode10 = Encoding.GetEncoding("x-Chinese-CNS");
}
